import os
import datetime
import uuid
from peewee import *
from werkzeug.security import generate_password_hash, check_password_hash

# 确保数据目录存在
data_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
os.makedirs(data_dir, exist_ok=True)

# 数据库连接（延迟初始化）
db = SqliteDatabase(None)

class BaseModel(Model):
    """基础模型类"""
    class Meta:
        database = db

class User(BaseModel):
    """用户模型"""
    username = CharField(unique=True, max_length=50)
    password_hash = CharField()
    email = CharField(null=True, max_length=100)
    is_admin = BooleanField(default=False)
    avatar = TextField(null=True)
    created_at = DateTimeField(default=datetime.datetime.now)

    def set_password(self, password):
        """设置密码哈希"""
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        """验证密码"""
        return check_password_hash(self.password_hash, password)

class APIKey(BaseModel):
    """API密钥模型"""
    user = ForeignKeyField(User, backref='api_keys', on_delete='CASCADE')
    key = CharField(unique=True, max_length=32)
    description = CharField(default="默认API密钥", max_length=100)
    is_active = BooleanField(default=False)
    is_revoked = BooleanField(default=False)
    created_at = DateTimeField(default=datetime.datetime.now)
    activated_at = DateTimeField(null=True)
    activated_by = ForeignKeyField(User, null=True, backref='activated_keys', on_delete='SET NULL')

    def generate_key(self):
        """生成新的API密钥"""
        self.key = f"sk-{str(uuid.uuid4()).replace('-', '')[:16]}"
    
    def to_json(self):
        return 

class ChatSession(BaseModel):
    """聊天会话模型"""
    user = ForeignKeyField(User, backref='chat_sessions', on_delete='CASCADE')
    title = CharField(default="新话题", max_length=100)
    created_at = DateTimeField(default=datetime.datetime.now)
    updated_at = DateTimeField(default=datetime.datetime.now)

    def save(self, *args, **kwargs):
        """保存时更新时间戳"""
        self.updated_at = datetime.datetime.now()
        super().save(*args, **kwargs)

class ChatMessage(BaseModel):
    """聊天消息模型"""
    session = ForeignKeyField(ChatSession, backref='messages', on_delete='CASCADE')
    role = CharField(max_length=10)  # 'user' 或 'assistant'
    content = TextField()
    created_at = DateTimeField(default=datetime.datetime.now)

class AIServer(BaseModel):
    """AI服务器模型"""
    name = CharField(max_length=50)
    url = TextField()
    description = TextField(null=True)
    is_active = BooleanField(default=True)
    created_at = DateTimeField(default=datetime.datetime.now)
    updated_at = DateTimeField(default=datetime.datetime.now)

    def save(self, *args, **kwargs):
        self.updated_at = datetime.datetime.now()
        super().save(*args, **kwargs)

class AIModel(BaseModel):
    """AI模型模型"""
    server = ForeignKeyField(AIServer, backref='models', on_delete='CASCADE')
    name = CharField(max_length=50)
    description = TextField(null=True)
    is_active = BooleanField(default=True)
    created_at = DateTimeField(default=datetime.datetime.now)
    updated_at = DateTimeField(default=datetime.datetime.now)

    def save(self, *args, **kwargs):
        self.updated_at = datetime.datetime.now()
        super().save(*args, **kwargs)

class SystemConfig(BaseModel):
    """系统配置模型"""
    key = CharField(unique=True, max_length=50)
    value = TextField()
    description = TextField(null=True)
    updated_at = DateTimeField(default=datetime.datetime.now)
    updated_by = ForeignKeyField(User, backref='config_changes', on_delete='SET NULL')

    @classmethod
    def get_default(cls, key: str) -> str | None:
        """获取默认配置值"""
        try:
            return cls.get(cls.key == key).value
        except DoesNotExist:
            return None

    @classmethod
    def set_default(cls, key: str, value: str, user: User):
        """设置默认配置值"""
        config, created = cls.get_or_create(
            key=key,
            defaults={'value': value, 'updated_by': user}
        )
        if not created:
            config.value = value
            config.updated_at = datetime.datetime.now()
            config.updated_by = user
            config.save()
        return config

def init_db():
    """初始化数据库"""
    # 创建所有表
    with db:
        db.create_tables([
            User, APIKey, ChatSession, ChatMessage,
            AIServer, AIModel, SystemConfig
        ])
    
    # 创建默认管理员（如不存在）
    if not User.select().where(User.username == 'admin').exists():
        admin = User(username='admin', is_admin=True, email='admin@example.com')
        admin.set_password('admin123')  # 首次登录后应修改
        admin.save()
